const {
    response
} = require("express")
const express = require("express")
const {
    request
} = require("http")
const path = require("path")

const app = express()

app.use("/post", (request, response, next) => {
    let userData = ""
    request.on("data", chunk => {
        userData += chunk.toString()
    })
    request.on("end", () => {

        // console.log(userData); //name=liuMin&age=31&sex=m
        // console.log(userData.split("&")) //[ 'name=liuMin', 'age=31', 'sex=m' ]

        // 方法1：
        // const o = {}
        // userData.split("&").forEach(item => {
        //     // console.log(item.split("="));
        //     const [
        //         key,
        //         value
        //     ] = item.split("=")
        //     o[key] = value
        // })
        // console.log(o);


        // 方法2:
        // console.log(userData); //name=liuMin&age=31&sex=m
        // console.log(userData.split("&")) //[ 'name=liuMin', 'age=31', 'sex=m' ]
        const o = userData.split("&").reduce((prev, current) => {
            const [
                key,
                value
            ] = current.split("=")

            prev[key] = value

            return prev
        }, {})
        // console.log(o);
        request.body = o
        next()
    })
})

app.all("/get", (request, response) => {
    const {
        userId
    } = request.query
    console.log(userId);
    if (userId !== "001") {
        return response.send({
            code: 10001,
            msg: "查询失败",
            data: null
        })
    }

    response.send({
        code: 10000,
        msg: "查询成功",
        data: {
            name: "liuMin",
            sex: "男",
            age: 31
        }
    })
})

app.all("/post", (request, response) => {
    console.log(request.body);
    // response.send(request.body)  { name: 'liuMin', age: '31', sex: 'm' }
    const {
        name,
        age,
        sex
    } = request.body

    if (!name || !age || !sex) {
        return response.send({
            code: 10001,
            msg: "请求失败",
            data: null
        })
    }
    response.send({
        code: 10000,
        msg: "请求成功",
        data: {
            name: "liuMin",
            age: 31,
            sex: "m"
        }
    })

})

app.all("/1", (request, response) => {
    const pathFile = path.resolve(__dirname, "./03.基础的get请求(1).html")
    response.sendFile(pathFile)
})

app.all("/2", (request, response) => {
    const pathFile = path.resolve(__dirname, "./04.post请求(1).html")
    response.sendFile(pathFile)
})



app.listen(8181, () => {
    console.log("服务器开启成功，请前往127.0.0.1:8181");
})